<template>
  <div
      class="clean-robot"
      :style="{ left: modelValue.x + 'px', top: modelValue.y + 'px' }"
      @mousedown="startDrag"
      @mouseenter="showControls = true"
      @mouseleave="showControls = false"
  >
    <img
        src="@/assets/robot.png"
        class="robot-avatar"
        alt="AI机器人"
    />

    <!-- 提示消息气泡 -->
    <div v-show="showControls" class="robot-message">
      <p>我可以帮助主人快速清理</p>
      <p>这个软件存储的本地文件垃圾</p>
    </div>

    <div v-show="showControls" class="robot-controls">
      <el-button type="primary" circle @click="openCleanDialog">
        <el-icon><Delete /></el-icon>
      </el-button>
    </div>

    <!-- 清理对话框 -->
    <el-dialog
        title="清理数据"
        v-model="dialogVisible"
        width="30%"
        :before-close="handleClose"
        class="custom-clean-dialog"
        :close-on-click-modal="false"
        :append-to-body="true"
    >
      <div class="clean-dialog-content">
        <!-- 输入要删除的数据库名称 -->
        <el-form-item label="数据库名称">
          <el-input
              v-model="databaseName"
              placeholder="输入要删除的数据库名称"
          ></el-input>
          <el-button
              type="primary"
              size="small"
              class="delete-single-btn"
              @click="deleteSingleDatabase"
              :disabled="!databaseName"
          >
            删除指定数据库
          </el-button>
        </el-form-item>

        <!-- 清除所有数据库 -->
        <el-button
            type="danger"
            class="clean-all-btn"
            @click="confirmCleanAllDatabases"
        >
          <el-icon class="mr-1"><Delete /></el-icon>清除所有数据库
        </el-button>

        <!-- 清除所有AI对话信息 -->
        <el-button
            type="warning"
            class="clean-ai-btn"
            @click="confirmCleanAllAiConversations"
        >
          <el-icon class="mr-1"><MessageBox /></el-icon>清除所有AI对话信息
        </el-button>
      </div>
    </el-dialog>

    <!-- 确认对话框 -->
    <el-dialog
        title="确认操作"
        v-model="confirmDialogVisible"
        width="30%"
        class="custom-confirm-dialog"
        :close-on-click-modal="false"
        :append-to-body="true"
    >
      <p>{{ confirmMessage }}</p>
      <template #footer>
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="executeConfirmedAction">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Delete, MessageBox } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {useClera}from '@/api/Table/clera.js'
const {clearAll, clearByName,clearDeepSeek} = useClera()
// 定义组件属性
const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
    default: () => ({ x: 20, y: 20 })
  }
})

// 定义组件事件
const emit = defineEmits([
  'update:modelValue',
  'deleteDatabase',
  'cleanAllDatabases',
  'cleanAllAiConversations'
])

// 状态管理
const showControls = ref(false)
const dialogVisible = ref(false)
const confirmDialogVisible = ref(false)
const confirmMessage = ref('')
const databaseName = ref('')
let currentAction = ref('')

// 拖拽相关变量
let isDragging = false
let dragStartX = 0
let dragStartY = 0

// 打开清理对话框
const openCleanDialog = () => {
  dialogVisible.value = true
  databaseName.value = ''
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  databaseName.value = ''
}

// 删除单个数据库
const deleteSingleDatabase = () => {
  if (!databaseName.value.trim()) {
    ElMessage.warning('请输入数据库名称')
    return
  }

  confirmMessage.value = `确定要删除数据库 "${databaseName.value}" 吗？此操作不可恢复。`
  currentAction.value = 'deleteSingle'
  confirmDialogVisible.value = true
}

// 确认清除所有数据库
const confirmCleanAllDatabases = () => {
  confirmMessage.value = '确定要清除所有数据库吗？此操作将删除所有数据，不可恢复。'
  currentAction.value = 'cleanAllDatabases'
  confirmDialogVisible.value = true
}

// 确认清除所有AI对话
const confirmCleanAllAiConversations = () => {
  confirmMessage.value = '确定要清除所有AI对话信息吗？此操作不可恢复。'
  currentAction.value = 'cleanAllAiConversations'
  confirmDialogVisible.value = true
}

// 执行确认的操作
const executeConfirmedAction = () => {
  confirmDialogVisible.value = false
  dialogVisible.value = false
  switch (currentAction.value) {
    case 'deleteSingle':
      clearByName({
        databaseName: databaseName.value,
      })
      emit('deleteDatabase', databaseName.value)
      ElMessage.success(`数据库 "${databaseName.value}" 已删除`)
      break
    case 'cleanAllDatabases':
      clearAll();
      emit('cleanAllDatabases')
      ElMessage.success('所有数据库已清除')
      break
    case 'cleanAllAiConversations':
      clearDeepSeek();
      emit('cleanAllAiConversations')
      ElMessage.success('所有AI对话信息已清除')
      break
  }

  databaseName.value = ''
}

// 开始拖拽
const startDrag = (e: MouseEvent) => {
  e.stopPropagation()
  isDragging = true
  dragStartX = e.clientX - props.modelValue.x
  dragStartY = e.clientY - props.modelValue.y
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('mouseup', stopDrag)
}

// 拖拽中
const handleDrag = (e: MouseEvent) => {
  if (!isDragging) return

  // 限制拖拽范围在可视区内
  const windowWidth = window.innerWidth
  const windowHeight = window.innerHeight
  const robotWidth = 40
  const robotHeight = 40

  let newX = e.clientX - dragStartX
  let newY = e.clientY - dragStartY

  // 边界限制
  newX = Math.max(0, Math.min(newX, windowWidth - robotWidth))
  newY = Math.max(0, Math.min(newY, windowHeight - robotHeight))

  emit('update:modelValue', { x: newX, y: newY })
}

// 停止拖拽
const stopDrag = () => {
  isDragging = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}
</script>

<style scoped>
.clean-robot {
  position: fixed;
  cursor: move;
  z-index: 1000;
  width: auto;
  height: auto;
  transition: transform 0.2s;
  will-change: transform;
  pointer-events: auto;

  &:hover {
    transform: scale(1.1);
  }
}

.robot-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid var(--el-color-primary);
}

.robot-controls {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
  background: rgba(255,255,255,0.9);
  padding: 4px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 消息气泡样式 */
.robot-message {
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%) translateY(-8px);
  background: rgba(255, 255, 255, 0.95);
  color: #333;
  padding: 6px 12px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
  font-size: 12px;
  white-space: nowrap;
  z-index: 1001;
}

.robot-message::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border-width: 5px;
  border-style: solid;
  border-color: rgba(255, 255, 255, 0.95) transparent transparent transparent;
}

/* 对话框内容样式 */
.clean-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.delete-single-btn {
  margin-top: 8px;
}

.clean-all-btn, .clean-ai-btn {
  width: 100%;
  justify-content: center;
}

/* 对话框样式优化 */
:deep(.custom-clean-dialog), :deep(.custom-confirm-dialog) {
  z-index: 3000 !important;

  .el-dialog__wrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .el-dialog {
    position: relative;
    width: 100%;
    max-width: 500px;
    margin: 0 auto;
  }
}
</style>
